# 引入ui
from untitled import Ui_MainWindow

# 引入默认工具类
import sys, time, os
import numpy as np
import matplotlib.pyplot as plt
import cv2
from tqdm import tqdm
from PIL import Image

# 引入gui工具
from pyqt5_plugins.examplebuttonplugin import QtGui
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import QLabel, QFileDialog, QApplication, QStyleFactory, QMainWindow, QMessageBox
from PyQt5.QtGui import QImage, QPixmap, QPen, QPainter

# 引入自定义工具类
import uiTools.saveAsExl, uiTools.feature, uiTools.show
import aug_tools.augmentations, aug_tools.transforms
import detect
import shutil
from catboost import CatBoostClassifier
from videoCapture import videoCapture
from preProcess import preProcess
from FeatureCal import FeatureCal
from dataFind import dataFind
from heightCal import heightCal
from wFeatureCal import wFeatureCal
from cutSludge import cutSludge
from wuCal import wuCal
import gen_images, joint

# 环境变量
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"


# 截取图片类
class ImageLabel(QLabel):
    '''获取用户裁剪坐标点，画线
        Attributes:
            points:用户点击的裁剪点
        '''

    def __init__(self, parent=None):
        super(ImageLabel, self).__init__(parent)
        self.points = []

    # normal function
    def show_image(self, image):
        # 参数image为np.array类型
        rgb_image = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2RGB)
        frame_width = image.shape[1]
        frame_height = image.shape[0]
        print("yuantu", frame_height, frame_width)
        print("rgbtu", rgb_image.shape[0], rgb_image.shape[1])

        # ratio=frame_width/frame_height
        # if (frame_width/frame_height)<(1100/600):
        #     frame_height=600
        #     frame_width=int(600*ratio)
        # else:
        #     frame_width=1100
        #     frame_height=int(1100/ratio)
        # rgb_image = cv2.resize(rgb_image, (frame_width, frame_height))
        label_image = QImage(rgb_image.data, rgb_image.shape[1], rgb_image.shape[0], rgb_image.shape[1] * 3,
                             QImage.Format_RGB888)
        print("label im", label_image)
        self.setPixmap(QPixmap(label_image))

    def reselect(self):
        self.points.clear()
        self.update()

    def get_points(self):
        return self.points

    # slot function
    # 根据点过的点来画图
    def paintEvent(self, event):
        QLabel.paintEvent(self, event)
        painter = QPainter()
        painter.begin(self)

        pen = QPen(Qt.red, 4, Qt.DashDotLine)  # 虚线画笔
        painter.setPen(pen)

        for k in range(len(self.points)):
            if k == 0:
                painter.drawLine(self.points[k][0], self.points[k][1], self.points[0][0], self.points[0][1])
            else:
                painter.drawLine(self.points[0][0], self.points[0][1], self.points[0][0], self.points[1][1])
                painter.drawLine(self.points[0][0], self.points[0][1], self.points[1][0], self.points[0][1])
                painter.drawLine(self.points[1][0], self.points[0][1], self.points[1][0], self.points[1][1])
                painter.drawLine(self.points[0][0], self.points[1][1], self.points[1][0], self.points[1][1])
        painter.end()

    # 开启标记功能时，获取点击坐标
    def mouseReleaseEvent(self, event):
        if len(self.points) < 2:
            global_point = event.globalPos()
            local_point = self.mapFromGlobal(global_point)

            point_x = local_point.x()
            point_y = local_point.y()
            self.points.append([point_x, point_y])

            self.update()  # 获取鼠标点击的点之后，通知画线


# main窗口类
class MainApp(QMainWindow, Ui_MainWindow):
    ok_signal = pyqtSignal()

    # 定义构造方法
    def __init__(self):
        QMainWindow.__init__(self)
        # 初始化ui
        self.setupUi(self)
        # 初始化绑定button
        self.handle_buttons()
        self.handle_ui_change()
        # 初始化绑定tab页切换
        self.open_start_tab()
        # 检测类型 0为默认  单张检测为1  文件夹多张检测为2
        self.detectType = 0
        # 当选择检测一个文件夹的时候，其中保存当前文件夹中所有以bmp,jpg,png结尾的文件名称
        self.picArray = []

    # UI变化处理
    def handle_ui_change(self):
        self.tabWidget.tabBar().setVisible(False)
        self.groupBox.setStyleSheet(("border:none"))
        self.groupBox_2.setStyleSheet(("border:none"))
        self.groupBox_3.setStyleSheet(("border:none"))
        self.groupBox_4.setStyleSheet(("border:none"))
        self.groupBox_5.setStyleSheet(("border:none"))

    # 所有Button的消息与槽的通信
    def handle_buttons(self):
        # ----------------------- tab页面切换绑定 -----------------------
        # 选择打开文件 打开文件并转入抽样tab
        self.action_open.triggered.connect(self.vLuJing)
        # 视频抽样tab切换
        self.action_chouYang.triggered.connect(self.open_chouYang_tab)
        # 抽样图片预处理tab切换
        self.action_pre.triggered.connect(self.open_yuChuLi_tab)
        # 给水图片特征计算tab切换
        self.action_cal.triggered.connect(self.open_teZheng_tab)
        # 给水图片特征计算结果查询tab切换
        self.action_find.triggered.connect(self.open_jieGuo_tab)
        # 给水图片出水浊度分类tab切换
        self.action_classify.triggered.connect(self.open_classify_tab)
        # 污水图片特征计算tab切换
        self.action_cal_w.triggered.connect(self.open_teZheng_tab_w)
        # 污水图片特征计算查询tab切换
        self.action_find_w.triggered.connect(self.open_jieGuo_tab_w)
        # 微生物目标检测tab切换
        self.action_micro_detect.triggered.connect(self.open_detect_tab_page)
        # 微生物目标数据集增广tab切换
        self.action_micro_aug.triggered.connect(self.open_aug_tab_page)

        # ----------------------- 视频截取抽样部分 页面按钮功能通信 -----------------------
        # 重新选择采样区域按钮
        self.reselect_button.clicked.connect(self.on_reselect_button)
        # 抽样图像保存路径选择按钮
        self.chouYang_path_save_button.clicked.connect(self.caiBaoCun)
        # 开始采样按钮
        self.push1_Button.clicked.connect(self.videoCap)

        # ----------------------- 图片预处理部分 页面按钮功能通信 -----------------------
        # 图片预处理路径选择
        self.preProce_path_button.clicked.connect(self.preProce_path_button_func)
        # 预处理结果保存路径选择
        self.preProce_path_save_button.clicked.connect(self.preProce_path_save_button_func)
        # 点击按钮开始预处理
        self.preProce_submit_button.clicked.connect(self.preProce_submit_func)

        # ----------------------- 特征计算保存部分 页面按钮功能通信 -----------------------
        # 图片预处理路径选择
        self.feature_path_button.clicked.connect(self.feature_path_button_func)
        # 预处理结果保存路径选择
        self.feature_path_save_button.clicked.connect(self.feature_path_save_button_func)
        # 特征计算开始计算
        self.feature_submit_button.clicked.connect(self.feature_submit_func)

        # ----------------------- 净水特征结果查询界面部分 页面按钮功能通信 -----------------------
        # 选择特征保存文件
        self.data_path_button.clicked.connect(self.data_path_button_func)
        # 特征结果查询
        self.data_submit_button.clicked.connect(self.data_submit_button_func)

        # ----------------------- 污水特征计算&结果查询界面部分 页面按钮功能通信 -----------------------
        # 污泥特征计算相关button 具体参考ui内容
        self.data_path_button_2.clicked.connect(self.data_path_button_2_func)
        self.data_path_button_3.clicked.connect(self.data_path_button_3_func)
        self.data_submit_button_2.clicked.connect(self.data_submit_button_2_func)
        self.data_submit_button_3.clicked.connect(self.data_submit_button_3_func)
        self.data_submit_button_4.clicked.connect(self.data_submit_button_4_func)
        self.feature_path_save_button_2.clicked.connect(self.feature_path_save_button_2_func)
        self.feature_submit_button_2.clicked.connect(self.feature_submit_button_2_func)

        # ----------------------- 浊度分类预警部分功能绑定 -----------------------
        # 输入相关特征后进行浊度分类
        self.classify_button.clicked.connect(self.classify_button_func)

        # ----------------------- 微生物检测按钮绑定 -----------------------
        # 选择待检测图片
        self.selectFile.clicked.connect(self.onSelectPicFile)
        # 选择待检测图片文件
        self.selectFileDir.clicked.connect(self.onSelectPicFileDir)
        # 选择结果保存路径
        self.selectSavePath.clicked.connect(self.onSelectSavePath)
        # 开始检测
        self.detect.clicked.connect(self.onDetectPic)

        # ----------------------- 增广部分功能绑定 -----------------------
        # 选择对比度图片文件夹
        self.pushButtonContrast.clicked.connect(self.onSelectContrastFileDir)
        # 选择对比度增强保存路径
        self.pushButtonContrastSave.clicked.connect(self.onSelectContrastSavePath)
        # 选择对比度标签文件夹
        self.pushButtonContrastLabel.clicked.connect(self.onSelectContrastLabelPath)
        # 开始对比度增强
        self.contrastConfirm.clicked.connect(self.onContrastPic)

        # 选择翻转图片文件夹
        self.pushButtonReverse.clicked.connect(self.onSelectReverseFileDir)
        # 选择翻转增强保存路径
        self.pushButtonReverseSave.clicked.connect(self.onSelectReverseSavePath)
        # 选择翻转增强标签路径
        self.pushButtonReverseLabel.clicked.connect(self.onSelectReverseLabelPath)
        # 开始旋转增强按钮
        self.reverseConfirm.clicked.connect(self.onReversePic)

        # 选择旋转图片文件夹
        self.pushButtonVein.clicked.connect(self.onSelectVeinFileDir)
        # 选择旋转增强保存路径
        self.pushButtonVeinSave.clicked.connect(self.onSelectVeinSavePath)
        # 选择旋转增强标签路径
        self.pushButtonVeinLabel.clicked.connect(self.onSelectVeinLabelPath)
        # 开始纹理增强按钮
        self.veinConfirm.clicked.connect(self.onVeinPic)
        # 选择gan增广结果保存路径
        self.pushButtonGAN.clicked.connect(self.onSelectGANSavePath)
        # 开始gan增广按钮
        self.ganConfirm.clicked.connect(self.onGANPic)

    # ----------------------- 选项卡联动切换tab切换 -----------------------
    def open_start_tab(self):
        self.tabWidget.setCurrentIndex(0)

    def open_chouYang_tab(self):
        self.tabWidget.setCurrentIndex(1)
        self.chouYang_save_lineEdit.setText("D:/python/picture_or")

    def open_yuChuLi_tab(self):
        self.tabWidget.setCurrentIndex(2)
        self.preProce_path.setText(self.chouYang_save_lineEdit.text())
        self.preProce_path_save.setText("D:/python/picture_gr")
        self.gauss_para.setText("30")
        self.median_para.setText("3")

    def open_teZheng_tab(self):
        self.tabWidget.setCurrentIndex(3)
        self.feature_path.setText(self.preProce_path_save.text())
        self.feature_save_path.setText("D:/python/excel")

    def open_teZheng_tab_w(self):
        self.tabWidget.setCurrentIndex(5)
        self.wuProcess_path.setText(self.chouYang_save_lineEdit.text())
        self.feature_save_path_2.setText("D:/python/excel")

    def open_jieGuo_tab(self):
        self.tabWidget.setCurrentIndex(4)
        self.data_path.setText(self.feature_save_path.text() + "/excel.xlsx")

    def open_classify_tab(self):
        self.tabWidget.setCurrentIndex(7)

    def open_jieGuo_tab_w(self):
        self.tabWidget.setCurrentIndex(6)
        self.data_path.setText(self.feature_save_path_2.text() + "/excel.xlsx")

    def open_detect_tab_page(self):
        self.tabWidget.setCurrentIndex(9)

    def open_aug_tab_page(self):
        self.tabWidget.setCurrentIndex(8)

    # ----------------------- 污泥特征查询相关按钮功能 -----------------------
    def feature_submit_button_2_func(self):
        wuCal(self.wuProcess_path.text(), self.feature_save_path_2.text())
        msg_box = QMessageBox(QMessageBox.Information, '成功', '已经计算并保存!')
        msg_box.exec_()
        self.open_jieGuo_tab_w()

    def feature_path_save_button_2_func(self):
        self.feature_save_path_2.setText(QFileDialog.getExistingDirectory())

    def data_path_button_2_func(self):
        self.wuProcess_path.setText(QFileDialog.getExistingDirectory())

    def data_path_button_3_func(self):
        self.data_path_2.setText(QFileDialog.getOpenFileName()[0])

    def data_submit_button_2_func(self):
        heightCal(self.data_path_2.text(), int(self.gray_type_4.currentIndex()))

    def data_submit_button_3_func(self):
        cutSludge(self.data_path_2.text(), int(self.gray_type_7.currentIndex()))

    def data_submit_button_4_func(self):
        wFeatureCal(self.data_path_2.text(), int(self.gray_type_6.currentIndex()))

    # ----------------------- 抽样相关功能 -----------------------
    # 截取位置取消按钮重新选择采样区域
    def on_reselect_button(self):
        self.image_label.reselect()

    # 抽样图像保存路径选择按钮
    def caiBaoCun(self):
        self.chouYang_save_lineEdit.setText(QFileDialog.getExistingDirectory())

    # 预览图片截取 操作相关采样区功能
    def preview(self):
        # 视频路径
        vc = cv2.VideoCapture(self.luJing_lineEdit.text())
        k = 0
        # 抽取第50帧进行预览
        while k < 50:
            vc.read()
            k = k + 1
        rval, frame = vc.read()
        return frame

    def show_im(self):
        self.image = self.preview()
        print(self.image.shape[0], self.image.shape[1])
        # 设置宽高比
        frame_width = self.image.shape[1]
        frame_height = self.image.shape[0]
        w_h_ratio = frame_width / frame_height
        # w_h_ratio = self.label.width() * 1.0 / self.label.height()
        print(self.label.width())
        print(self.label.height())
        print("w_h_ration", w_h_ratio)
        print((int)(self.image.shape[0] * w_h_ratio))
        if (frame_width / frame_height) < (1100 / 600):
            frame_height = 600
            frame_width = int(600 * w_h_ratio)
        else:
            frame_width = 1100
            frame_height = int(1100 / w_h_ratio)
        print("h,w", frame_height, frame_width)
        self.image = cv2.resize(self.image, (frame_width, frame_height))

        self.image_label = ImageLabel(self.label)

        self.image_label.show_image(self.image)

    def get_image(self):
        return self.image

        # 根据左上、左下，右下，右上的顺序排序

    # 排列截取点
    def order_points(self, points):
        # 求中心点的坐标
        center = [0, 0]
        for point in points:
            center[0] += point[0]
            center[1] += point[1]
        center[0] = center[0] / 2
        center[1] = center[1] / 2
        print(center)
        # 根据中心点x坐标，大于为左，小于为右
        left = []
        right = []
        for point in points:
            if point[0] > center[0]:
                right.append(point)
            else:
                left.append(point)
        return [left, right]

    # 将截取点映射到原图像
    def mapfromLoal(self, points):
        # 从局部点投影到原图，并且将4个点的顺序，按照左上、左下，右下，右上的顺序排序
        points_origanal = []
        print("in map shape:", self.image.shape)
        print("before largen", points)

        y_ratio = np.float32(self.preview().shape[0] / self.image_label.height())
        x_ratio = np.float32(self.preview().shape[1] / self.image_label.width())
        for point in points:
            points_origanal.append([point[0] * x_ratio, point[1] * y_ratio])

        order_points = self.order_points(points_origanal)
        print("order", order_points)
        return order_points
        # return points_origanal

    # 提示信息
    # 采样前提示视频相关信息
    def show1(self):
        vc = cv2.VideoCapture(self.luJing_lineEdit.text())
        fps = vc.get(cv2.CAP_PROP_FPS)
        fps = round(fps, 2)
        frame_all = vc.get(cv2.CAP_PROP_FRAME_COUNT)
        time_all = frame_all / fps
        time_all = round(time_all, 2)
        frame_interval = int(int(self.jianGe_lineEdit.text()) * fps)
        count_p = int(frame_all / frame_interval)
        reply = QMessageBox.about(self, "视频相关信息", "视频FPS: {}每秒<br /> 视频总帧数: {}< br />"
                                                  " 视频时长：{}秒< br />共需保存： {}张图片< br />".format(fps, frame_all, time_all,
                                                                                              count_p))
        print(reply)

    # 采样后提示采样图片集相关信息
    def show2(self):
        vc = cv2.VideoCapture(self.luJing_lineEdit.text())
        fps = vc.get(cv2.CAP_PROP_FPS)
        fps = round(fps, 2)
        frame_all = vc.get(cv2.CAP_PROP_FRAME_COUNT)
        frame_interval = int(int(self.jianGe_lineEdit.text()) * fps)
        count_p = int(frame_all / frame_interval)
        reply = QMessageBox.about(self, "", "成功保存{}张图片".format(count_p))
        print(reply)

    # 采样后展示部分图片
    def show3(self):
        vc = cv2.VideoCapture(self.luJing_lineEdit.text())
        fps = vc.get(cv2.CAP_PROP_FPS)
        fps = round(fps, 2)
        frame_all = vc.get(cv2.CAP_PROP_FRAME_COUNT)
        frame_interval = int(self.jianGe_lineEdit.text()) * fps
        count_p = int(frame_all / frame_interval)
        ratio = int(count_p / 15)
        sa = self.chouYang_save_lineEdit.text()
        # if (self.baoCun_lineEdit.text() != ""):
        #     sa = self.baoCun_lineEdit.text()
        N = 5
        M = 3
        plt.figure(figsize=(60, 30))
        plt.figure(1)
        # 形成NxM大小的画布
        for i in range(15):
            path = sa + '/picture-' + str(i * ratio) + '.jpg'
            img = plt.imread(path)
            plt.subplot(N, M, int(i) + 1)  # 表示第i张图片，下标只能从1开始，不能从0，
            plt.title(str(i * ratio + 1), fontsize=15, pad=2)
            plt.imshow(img)
            # 下面两行是消除每张图片自己单独的横纵坐标，不然每张图片会有单独的横纵坐标，影响美观
            plt.xticks([])
            plt.yticks([])
        plt.show()

    # 文件路径选择
    def vLuJing(self):
        self.luJing_lineEdit.setText(QFileDialog.getOpenFileName()[0])
        self.show_im()
        self.open_chouYang_tab()

    # 视频抽样具体功能
    def videoCap(self):
        self.show1()
        # self.setCursor(Qt.WaitCursor)
        points = self.image_label.get_points()
        # 单适应变换
        print("points", points)
        points_origanal = self.mapfromLoal(points)

        print("src_point", points_origanal)
        print(points_origanal[0][0][1])
        h1 = int(points_origanal[0][0][1])
        h2 = int(points_origanal[1][0][1])
        w1 = int(points_origanal[0][0][0])
        w2 = int(points_origanal[1][0][0])
        path = self.chouYang_save_lineEdit.text()

        videoCapture(self.luJing_lineEdit.text(), self.jianGe_lineEdit.text(), h1, h2, w1, w2,
                     self.chouYang_save_lineEdit.text())
        # tkinter.Button(self, text='cursor_style', cursor='arrow').pack()
        # self.setCursor(Qt.SizeAllCursor)
        self.show2()
        self.show3()
        if int(self.gray_type_3.currentIndex()) == 0:
            self.open_yuChuLi_tab()
        else:
            self.open_teZheng_tab_w()


    # ----------------------- 预处理相关 -----------------------
    # 截取图片保存的路径选择
    def preProce_path_button_func(self):
        self.preProce_path.setText(QFileDialog.getExistingDirectory())

    # 保存路径选择
    def preProce_path_save_button_func(self):
        self.preProce_path_save.setText(QFileDialog.getExistingDirectory())

    # 点击提交按钮的功能
    def preProce_submit_func(self):
        # self.preProce_path.setText(QFileDialog.getExistingDirectory())
        # if self.preProce_path.text() == '' or self.pic_start.text() == '' or self.pic_end.text() == '' or self.preProce_gap.text() == '' or self.preProce_path_save.text() == '':
        #     msg_box = QMessageBox(QMessageBox.Warning, '提示', '请确保全部信息都完整输入!')
        #     msg_box.exec_()
        # else:
        path = self.preProce_path.text()
        count = 0
        for file in os.listdir(path):  # file 表示的是文件名
            count = count + 1
        print(count)
        preProcess(self.preProce_path.text(), 1, 0,
                   count - 1, int(self.gray_type.currentIndex()),
                   self.preProce_path_save.text(), int(self.gauss_para.text()),
                   int(self.median_para.text()), )

        msg_box = QMessageBox(QMessageBox.Information, '成功', '已完成预处理操作!')
        msg_box.exec_()
        self.show_pre()
        self.open_teZheng_tab()
        # print('path', self.preProce_path.text())
        # print('gap', self.preProce_gap.text())
        # print('pic_start', self.pic_start.text())
        # print('pic_end', self.pic_end.text())
        # print('path_save', self.preProce_path_save.text())
        # # 获取下拉列表框中选择的内容
        # print('gray_type', self.gray_type.currentText())
        # # 获取下拉列表框中选择的内容的索引下标
        # print('gray_type_index', self.gray_type.currentIndex())

    # 预处理后预览效果
    def show_pre(self):
        path = self.preProce_path.text()
        count = 0
        for file in os.listdir(path):  # file 表示的是文件名
            count = count + 1
        ratio = int(count / 5)
        print(ratio)
        N = 5
        M = 2
        # 形成NxM大小的画布
        plt.figure(figsize=(32, 16))
        plt.figure(1)
        for i in range(5):
            path = self.preProce_path.text() + '/picture-' + str(i * ratio) + '.jpg'
            path1 = self.preProce_path_save.text() + '/gray-' + str(i * ratio) + '.png'

            img = plt.imread(path)
            img1 = plt.imread(path1)
            plt.subplot(N, M, int(i * 2) + 1)  # 表示第i张图片，下标只能从1开始，不能从0，
            if i == 0:
                plt.title('Original Image', fontsize=25, pad=15)
            plt.imshow(img, cmap="gray")
            # 下面两行是消除每张图片自己单独的横纵坐标，不然每张图片会有单独的横纵坐标，影响美观
            plt.xticks([])
            plt.yticks([])

            plt.subplot(N, M, int(i * 2) + 2)  # 表示第i张图片，下标只能从1开始，不能从0，
            if i == 0:
                plt.title('Processed Image', fontsize=25, pad=15)
            plt.imshow(img1, cmap="gray")
            # 下面两行是消除每张图片自己单独的横纵坐标，不然每张图片会有单独的横纵坐标，影响美观
            plt.xticks([])
            plt.yticks([])
            print(i)
        plt.show()


    # 净水预处理特征计算相关功能 图片路径&保存路径&开始特征计算
    def feature_path_button_func(self):
        self.feature_path.setText(QFileDialog.getExistingDirectory())

    def feature_path_save_button_func(self):
        self.feature_save_path.setText(QFileDialog.getExistingDirectory())

    def feature_submit_func(self):
        # print('图片路径?', self.feature_path.text())
        # print('图片间隔?', int(self.feature_gap.text()))
        # print('图片起始张数?', int(self.feature_pic_start.text()))
        # print('图片结束张数?', int(self.feature_pic_end.text()))
        # print('高斯模糊系数?', int(self.gauss_para.text()))
        # print('中值滤波系数?', int(self.median_para.text()))
        # # feature_number.isChecked() 检查复选框是否被选中 选中是True 没选中是False
        # print('絮体个数选中?', self.feature_number.isChecked())
        # print('絮体面积选中?', self.feature_area.isChecked())
        # print('等效直径选中?', self.ad.isChecked())
        # print('角二阶矩选中?', self.gray_asm.isChecked())
        # print('能量选中?', self.gray_energy.isChecked())
        # print('对比度选中?', self.feature_contrast.isChecked())
        # print('逆差矩选中?', self.feature_homo.isChecked())
        # print('相关系数选中?', self.feature_conrela.isChecked())
        # print('分形维数选中?', self.fractal_dimension.isChecked())
        # print('结果保存路径?', self.feature_save_path.text())
        path = self.feature_path.text()
        count = 0
        for file in os.listdir(path):  # file 表示的是文件名
            count = count + 1
        count = count - 1
        res = FeatureCal(self.feature_path.text(), 1,
                         0,
                         count, self.feature_save_path.text())
        msg_box = QMessageBox(QMessageBox.Information, '成功', '已经计算并保存!')
        msg_box.exec_()
        self.open_jieGuo_tab()
        # res.to_excel('./' + 'excel.xlsx')
        # print(res)

    # ----------------------- 结果查询页面部分 页面按钮功能通信  start ---------------------

    def data_path_button_func(self):
        self.data_path.setText(QFileDialog.getOpenFileName()[0])

    def data_submit_button_func(self):
        dataFind(self.data_path.text(), int(self.gray_type_2.currentIndex()))

    # ----------------------- 结果查询页面部分 页面按钮功能通信  end -----------------------

    # ----------------------- 浊度分类部分 -----------------------
    def classify_button_func(self):
        dosage = self.dosage.text()
        entopy = self.entopy.text()
        corelation = self.corelation.text()
        flocAd = self.flocAd.text()
        flocFd = self.flocFd.text()
        data = [float(dosage), float(entopy), float(corelation), float(flocAd), float(flocFd)]
        # 读取保存在根目录的模型
        loaded_model = CatBoostClassifier().load_model('./CatBoostModel/catboost_model.cbm')
        y_pred = loaded_model.predict(data)
        print(y_pred[0])
        if y_pred[0] == '合格':
            self.classify_res.setText('当前絮体图像特征对应浊度分类为 [合格]\n对应浊度区间为 0-1 NTU.')
        elif y_pred[0] == '警告':
            self.classify_res.setText('当前絮体图像特征对应浊度分类为 [警告]\n对应浊度区间为 1-3 NTU.')
        else:
            self.classify_res.setText('当前絮体图像特征对应浊度分类为 [不合格]\n对应浊度区间为 大于3 NTU.')

    # ----------------------- 微生物目标检测 & 增广 -----------------------
    # 选择待检测图片
    def onSelectPicFile(self):
        # 选择待检测的图片,展示在待检测区
        filename, filetype = QFileDialog.getOpenFileName(self, '请选择待检图片')
        self.singlePicPath = filename
        # 显示选择路径的指定图片
        jpg = QtGui.QPixmap(filename).scaled(self.imageShow.width(), self.imageShow.height())
        self.selectedFile.setText(filename)
        # self.selectedFile.setText(QFileDialog.getExistingDirectory(self, '请选择待检文件夹'))
        self.imageShow.setPixmap(jpg)
        # 调整检测类型为单张
        self.detectType = 1

        # 选择待检测图片文件
    def onSelectPicFileDir(self):
        # 选择文件夹路径
        self.selectedFile.setText(QFileDialog.getExistingDirectory(self, '请选择待检文件夹'))
        # 调整检测类型为文件夹多张
        self.detectType = 2
        # 选择文件夹时 仅展示文件夹中第一张图片
        self.picArray = []

        # 判断当前文件中是否存在以jpg、bmp、png为结尾的文件
        for root, dirs, files in os.walk(self.selectedFile.text()):
            for file in files:
                # 检测的目标个数
                ext = os.path.splitext(file)[-1].lower()
                # 用文件后缀名判断当前文件夹中是否有图片类型
                if ext == '.jpg' or ext == '.bmp' or ext == '.png':
                    self.picArray.append(file)

        # 当文件夹中图片的个数大于0的时候才会展示一张出来
        if len(self.picArray) > 0:
            self.DirFirstPicPath = self.selectedFile.text() + '/' + self.picArray[0]
            # 显示文件夹中的第一个图片
            jpg = QtGui.QPixmap(self.DirFirstPicPath).scaled(self.imageShow.width(), self.imageShow.height())
            self.imageShow.setPixmap(jpg)

        else:
            QMessageBox.information(self, '提示', '当前选择文件夹中不存在以jpg、bmp、png结尾的图片文件，请重新选择！', QMessageBox.Yes)
            self.selectedFile.setText('暂无,请点击左侧按钮选择路径')

        # 选择结果保存路径 是个文件夹就行
    def onSelectSavePath(self):
        self.selectedSavePath.setText(QFileDialog.getExistingDirectory())

        # 开始检测
    def onDetectPic(self):
        # 判断图片和保存路径是否选择 没选择就显示提示信息并不往下执行
        if self.selectedSavePath.text() == '暂无,请点击左侧按钮选择路径' and self.detectType == 1:
            QMessageBox.information(self, '提示', '请选择待检测图片路径!', QMessageBox.Yes)

        if self.selectedSavePath.text() == '暂无,请点击左侧按钮选择路径' and self.detectType == 2:
            QMessageBox.information(self, '提示', '请选择结果保存路径!', QMessageBox.Yes)

        # detectType为1时候，进行单张图片的检测
        elif self.selectedSavePath.text() != '暂无,请点击左侧按钮选择路径' and self.detectType == 1:
            # 图片保存文件夹设置为当前时间
            t = time.localtime()
            fileDirName = time.strftime("%Y-%m-%d-%H-%M-%S", t)
            # 在yolo的detect文件中重新创建了一个方法outSide,传入指定参数同样可以进行检测
            # 参数 source=待检测图片 savePath=结果保存路径 fileDirName=结果要保存在一个文件夹中
            detect.outSide(
                source=self.selectedFile.text(),
                savePath=self.selectedSavePath.text(),
                name=str(fileDirName)
            )

            # 通过检测结果保存的路径,在待检测区展示检测结果图
            picName = self.singlePicPath.split("/")
            picNameLast = picName[-1]
            showImagePath = str(self.selectedSavePath.text()) + '/' + str(fileDirName) + '/' + picNameLast
            jpg = QtGui.QPixmap(showImagePath).scaled(self.imageShowDetect.width(), self.imageShowDetect.height())
            self.imageShowDetect.setPixmap(jpg)

            # 统计检测出的目标个数
            countGranularSludge = 0
            countEpistylis = 0
            countFloc = 0
            countRotifer = 0
            countFilamentousbacteria = 0

            # # 一张图中所有颗粒污泥的实际直径
            # averageAd = []
            # averageFd = []
            # 循环读取裁剪出来的目标个数,统计检测结果
            for root, dirs, files in os.walk(
                    self.selectedSavePath.text() + "/" + fileDirName + "./crops/Granular Sludge/"):
                countGranularSludge = len(files)
                # for file in files:
                #     # 此处进行单张图片的特征计算
                #
                #     # 分割后的绝对路径
                #     absPath = self.selectedSavePath.text() + "/" + fileDirName + "./crops/Granular Sludge/" + file
                #     # 读取图片特征计算
                #
                #     # 计算每张图的最大颗粒粒径
                #     averageAd.append(uiTools.feature.featureCalculateAd(absPath))
                #     # 计算颗粒污泥分形
                #     averageFd.append(uiTools.feature.featureCalculateFd(absPath))

            for root, dirs, files in os.walk(self.selectedSavePath.text() + "/" + fileDirName + "./crops/Epistylis/"):
                countEpistylis = len(files)

            for root, dirs, files in os.walk(self.selectedSavePath.text() + "/" + fileDirName + "./crops/Rotifer/"):
                countRotifer = len(files)

            for root, dirs, files in os.walk(self.selectedSavePath.text() + "/" + fileDirName + "./crops/Floc/"):
                countFloc = len(files)

            for root, dirs, files in os.walk(
                    self.selectedSavePath.text() + "/" + fileDirName + "./crops/Filamentous bacteria/"):
                countFilamentousbacteria = len(files)

            # 拼接保存路径
            excelPath = str(self.selectedSavePath.text()) + '/' + str(fileDirName)

            # 把目标个数统计结果保存至excel
            uiTools.saveAsExl.saveDetectAsExl(excelPath,
                                              countGranularSludge,
                                              countEpistylis,
                                              countFloc,
                                              countRotifer,
                                              countFilamentousbacteria,
                                              )

            # 拼接结果保存的路径
            figurePath = excelPath + './' + fileDirName
            uiTools.show.savePic(excelPath, figurePath)

            # 读取保存的图片展示在gui
            figPath = str(self.selectedSavePath.text()) + '/' + str(fileDirName) + '/' + fileDirName + '.png'
            StatisticJpg = QtGui.QPixmap(figPath).scaled(self.imageShowStatis.width(), self.imageShowStatis.height())
            self.imageShowStatis.setPixmap(StatisticJpg)

        # detectType为2时候，进行一个文件夹中所有图片的检测
        elif self.selectedSavePath.text() != '暂无,请点击左侧按钮选择路径' and self.detectType == 2:
            # 图片保存文件夹设置为当前时间
            t = time.localtime()
            fileDirName = time.strftime("%Y-%m-%d-%H-%M-%S", t)
            # 在yolo的detect文件中重新创建了一个方法outSide,传入指定参数同样可以进行检测
            # 参数 source=待检测图片 savePath=结果保存路径 fileDirName=结果要保存在一个文件夹中
            detect.outSide(
                source=self.selectedFile.text(),
                savePath=self.selectedSavePath.text(),
                name=str(fileDirName)
            )

            # 只展示出待检测文件中第一张图片的检测结果，展示在界面上
            showImagePath = str(self.selectedSavePath.text()) + '/' + str(fileDirName) + '/' + self.picArray[0]
            jpg = QtGui.QPixmap(showImagePath).scaled(self.imageShowDetect.width(), self.imageShowDetect.height())
            self.imageShowDetect.setPixmap(jpg)

            # 统计文件夹中所有图片检测出的目标个数
            countGranularSludge = 0
            countEpistylis = 0
            countFloc = 0
            countRotifer = 0
            countFilamentousbacteria = 0

            detectedPicCount = 0
            for root, dirs, files in os.walk(self.selectedFile.text()):
                detectedPicCount = len(files)
                # print('一共有',detectedPicCount,'张图片被检测')
            for root, dirs, files in os.walk(
                    self.selectedSavePath.text() + "/" + fileDirName + "./crops/Granular Sludge/"):
                countGranularSludge = len(files)

            for root, dirs, files in os.walk(self.selectedSavePath.text() + "/" + fileDirName + "./crops/Epistylis/"):
                countEpistylis = len(files)

            for root, dirs, files in os.walk(self.selectedSavePath.text() + "/" + fileDirName + "./crops/Rotifer/"):
                countRotifer = len(files)

            for root, dirs, files in os.walk(self.selectedSavePath.text() + "/" + fileDirName + "./crops/Floc/"):
                countFloc = len(files)

            for root, dirs, files in os.walk(
                    self.selectedSavePath.text() + "/" + fileDirName + "./crops/Filamentous bacteria/"):
                countFilamentousbacteria = len(files)

            # 拼接保存路径
            excelPath = str(self.selectedSavePath.text()) + '/' + str(fileDirName)

            # 把目标个数统计结果保存至excel
            uiTools.saveAsExl.saveDetectAsExl(excelPath,
                                              countGranularSludge,
                                              countEpistylis,
                                              countFloc,
                                              countRotifer,
                                              countFilamentousbacteria,
                                              )

            # 同上
            figurePath = excelPath + './' + fileDirName
            epath = 'EXCEL/results.xls'
            empath = 'EXCEL/results_mean.xls'
            uiTools.show.savePicMulti(epath, empath, figurePath)

            figPath = str(self.selectedSavePath.text()) + '/' + str(fileDirName) + '/' + fileDirName + '.png'
            StatisticJpg = QtGui.QPixmap(figPath).scaled(self.imageShowStatis.width(), self.imageShowStatis.height())
            self.imageShowStatis.setPixmap(StatisticJpg)

    # 选择文件夹
    def onSelectContrastFileDir(self):
        # 选择文件夹路径
        self.contrastPath.setText(QFileDialog.getExistingDirectory(self, '请选择待检文件夹'))
        # 调整检测类型为文件夹多张
        self.detectType = 2
        # 选择文件夹时 仅展示文件夹中第一张图片
        self.picArray = []

        # 判断当前文件中是否存在以jpg、bmp、png为结尾的文件
        for root, dirs, files in os.walk(self.contrastPath.text()):
            for file in files:
                # 检测的目标个数
                ext = os.path.splitext(file)[-1].lower()
                # print(ext)
                if ext == '.jpg' or ext == '.bmp' or ext == '.png':
                    self.picArray.append(file)
                    print(self.picArray)

        # 当文件夹中图片的个数大于0的时候才会展示一张出来
        if len(self.picArray) > 0:
            self.DirFirstPicPath = self.contrastPath.text() + '/' + self.picArray[0]
            # 显示文件夹中的第一个图片
            jpg = QtGui.QPixmap(self.DirFirstPicPath).scaled(self.aug_pre_contrast.width(),
                                                             self.aug_pre_contrast.height())
            self.aug_pre_contrast.setPixmap(jpg)

        else:
            QMessageBox.information(self, '提示', '当前选择文件夹中不存在以jpg、bmp、png结尾的图片文件，请重新选择！', QMessageBox.Yes)

    def onSelectContrastLabelPath(self):
        # 选择数据集标签所在文件夹
        self.contrastPathLabel.setText(QFileDialog.getExistingDirectory())

    def onSelectContrastSavePath(self):
        # 选择结果保存路径
        self.contrastPathSave.setText(QFileDialog.getExistingDirectory())

    # 开始对比度增广
    def onContrastPic(self):
        # 获取文件下属性为imgProperty的所有文件
        def GetImgNameByEveryDir(file_dir, imgProperty):
            FileName = []
            for root, dirs, files in os.walk(file_dir):
                for file in files:
                    if os.path.splitext(file)[1] in imgProperty:
                        FileName.append(file)  # 保存图片名称
            return FileName

        def readBoxes(txt_path):
            boxes = []
            with open(txt_path) as file:
                txt_lines = file.readlines()
                for txt_line in txt_lines:
                    box = txt_line.rstrip().split(" ")
                    boxes.append([int(box[0]), float(box[1]), float(box[2]), float(box[3]), float(box[4])])

            return boxes

        image_path = self.contrastPath.text()
        label_path = self.contrastPathLabel.text()
        output_path = self.contrastPathSave.text()

        pho = str(self.photoPara.currentText())

        def get_class_value(className):
            if className == "对比度变换":
                return 0
            elif className == "亮度变换":
                return 1
            elif className == "饱和度变换":
                return 2

        phoId = get_class_value(pho)

        img_list = GetImgNameByEveryDir(image_path, ['.jpg', '.jpeg', '.bmp'])
        for img_name in tqdm(img_list):
            img_is_ok = 1
            boxes = []
            img_path = image_path + '\\' + img_name
            try:
                img = np.array(Image.open(img_path).convert('RGB'), dtype=np.uint8)
                img1 = cv2.imread(img_path)
            except Exception as e:
                print(f"could not read image '{img_path}'. ")
                img_is_ok = 0
            if img_is_ok:  # 如果图像存在，读取对应的标签文件
                label_name = img_name[:-3] + 'txt'
                txt_path = label_path + '\\' + label_name
                boxes = readBoxes(txt_path)
                print(boxes)

            # 根据选择内容 进行不同的增广
            if phoId == 0:
                if not os.path.exists(output_path):
                    os.makedirs(output_path)
                if not os.path.exists(os.path.join(output_path, 'Contrast')):
                    os.makedirs(os.path.join(output_path, 'Contrast'))
                if not os.path.exists(os.path.join(output_path, 'Contrast', 'aug_img')):
                    os.makedirs(os.path.join(output_path, 'Contrast', 'aug_img'))
                if not os.path.exists(os.path.join(output_path, 'Contrast', 'aug_label')):
                    os.makedirs(os.path.join(output_path, 'Contrast', 'aug_label'))
                    # 在aug_label文件夹创建classes.txt文件
                    with open(os.path.join(output_path, 'Contrast', 'aug_label', 'classes.txt'), 'w') as f:
                        f.write('Granular sludge\n')
                        f.write('Epistylis\n')
                        f.write('Floc\n')
                        f.write('Rotifer\n')
                        f.write('Filamentous bacteria\n')

                transform = aug_tools.augmentations.AUGMENTATION_TRANSFORMS_Contrast
                boxes = np.array(boxes)
                temp_boxes = np.zeros_like(boxes)
                temp_boxes[:, :] = boxes[:, :]
                #
                # copy_num为对同一张图片扩充的张数
                copy_num = 1  # 增强张数
                for i in np.arange(copy_num):
                    new_img, bb_target = transform((img1, boxes))
                    save_name = img_name[:-4] + "_Contrast_" + str(i)
                    cv2.imwrite(os.path.join(output_path, 'Contrast', 'aug_img', save_name + '.bmp'), new_img)
                    txt_file = open(os.path.join(output_path, 'Contrast', 'aug_label', save_name + '.txt'), 'w')
                    for line in bb_target:
                        bb = str(int(line[0])) + ' ' + str(line[1]) + ' ' + str(line[2]) + ' ' + str(
                            line[3]) + ' ' + str(
                            line[4]) + '\n'
                        txt_file.write(bb)
                    txt_file.close()
                    boxes[:, :] = temp_boxes[:, :]
                contrastPath = self.contrastPathSave.text() + '/' + 'Contrast' + '/' + 'aug_img'

            if phoId == 1:

                if not os.path.exists(output_path):
                    os.makedirs(output_path)
                if not os.path.exists(os.path.join(output_path, 'Brightness')):
                    os.makedirs(os.path.join(output_path, 'Brightness'))
                if not os.path.exists(os.path.join(output_path, 'Brightness', 'aug_img')):
                    os.makedirs(os.path.join(output_path, 'Brightness', 'aug_img'))
                if not os.path.exists(os.path.join(output_path, 'Brightness', 'aug_label')):
                    os.makedirs(os.path.join(output_path, 'Brightness', 'aug_label'))
                    # 在aug_label文件夹创建classes.txt文件
                    with open(os.path.join(output_path, 'Brightness', 'aug_label', 'classes.txt'), 'w') as f:
                        f.write('Granular sludge\n')
                        f.write('Epistylis\n')
                        f.write('Floc\n')
                        f.write('Rotifer\n')
                        f.write('Filamentous bacteria\n')

                transform = aug_tools.augmentations.AUGMENTATION_TRANSFORMS_Brightness
                boxes = np.array(boxes)
                temp_boxes = np.zeros_like(boxes)
                temp_boxes[:, :] = boxes[:, :]
                #
                # copy_num为对同一张图片扩充的张数
                copy_num = 1  # 增强张数
                for i in np.arange(copy_num):
                    new_img, bb_target = transform((img1, boxes))
                    save_name = img_name[:-4] + "_Brightness_" + str(i)
                    cv2.imwrite(os.path.join(output_path, 'Brightness', 'aug_img', save_name + '.bmp'), new_img)
                    txt_file = open(os.path.join(output_path, 'Brightness', 'aug_label', save_name + '.txt'), 'w')
                    for line in bb_target:
                        bb = str(int(line[0])) + ' ' + str(line[1]) + ' ' + str(line[2]) + ' ' + str(
                            line[3]) + ' ' + str(
                            line[4]) + '\n'
                        txt_file.write(bb)
                    txt_file.close()
                    boxes[:, :] = temp_boxes[:, :]
                contrastPath = self.contrastPathSave.text() + '/' + 'Brightness' + '/' + 'aug_img'

            elif phoId == 2:

                if not os.path.exists(output_path):
                    os.makedirs(output_path)
                if not os.path.exists(os.path.join(output_path, 'Saturation')):
                    os.makedirs(os.path.join(output_path, 'Saturation'))
                if not os.path.exists(os.path.join(output_path, 'Saturation', 'aug_img')):
                    os.makedirs(os.path.join(output_path, 'Saturation', 'aug_img'))
                if not os.path.exists(os.path.join(output_path, 'Saturation', 'aug_label')):
                    os.makedirs(os.path.join(output_path, 'Saturation', 'aug_label'))
                    # 在aug_label文件夹创建classes.txt文件
                    with open(os.path.join(output_path, 'Saturation', 'aug_label', 'classes.txt'), 'w') as f:
                        f.write('Granular sludge\n')
                        f.write('Epistylis\n')
                        f.write('Floc\n')
                        f.write('Rotifer\n')
                        f.write('Filamentous bacteria\n')

                transform = aug_tools.augmentations.AUGMENTATION_TRANSFORMS_HueAndSaturation
                boxes = np.array(boxes)
                temp_boxes = np.zeros_like(boxes)
                temp_boxes[:, :] = boxes[:, :]
                #
                # copy_num为对同一张图片扩充的张数
                copy_num = 1  # 增强张数
                for i in np.arange(copy_num):
                    new_img, bb_target = transform((img1, boxes))
                    save_name = img_name[:-4] + "_Saturation_" + str(i)
                    cv2.imwrite(os.path.join(output_path, 'Saturation', 'aug_img', save_name + '.bmp'), new_img)
                    txt_file = open(os.path.join(output_path, 'Saturation', 'aug_label', save_name + '.txt'), 'w')
                    for line in bb_target:
                        bb = str(int(line[0])) + ' ' + str(line[1]) + ' ' + str(line[2]) + ' ' + str(
                            line[3]) + ' ' + str(
                            line[4]) + '\n'
                        txt_file.write(bb)
                    txt_file.close()
                    boxes[:, :] = temp_boxes[:, :]
                contrastPath = self.contrastPathSave.text() + '/' + 'Saturation' + '/' + 'aug_img'

        self.picArray = []
        # reversePath = self.reversePathSave.text() + '/' + 'reverse' + '/' + 'aug_img'
        for root, dirs, files in os.walk(contrastPath):
            for file in files:
                # 检测的目标个数
                ext = os.path.splitext(file)[-1].lower()
                print(ext)
                if ext == '.jpg' or ext == '.bmp' or ext == '.png':
                    self.picArray.append(file)

        if len(self.picArray) > 0:
            self.DirFirstPicPath = contrastPath + '/' + self.picArray[0]
            # 显示文件夹中的第一个图片
            jpg = QtGui.QPixmap(self.DirFirstPicPath).scaled(self.aug_after_contrast.width(),
                                                             self.aug_after_contrast.height())
            self.aug_after_contrast.setPixmap(jpg)

        else:
            QMessageBox.information(self, '提示', '当前选择文件夹中不存在以jpg、bmp、png结尾的图片文件，请重新选择！', QMessageBox.Yes)

        # 选择纹理增广数据集图片路径
    def onSelectVeinFileDir(self):
        # 选择文件夹路径
        self.veinPath.setText(QFileDialog.getExistingDirectory(self, '请选择待检文件夹'))
        # 调整检测类型为文件夹多张
        self.detectType = 2
        # 选择文件夹时 仅展示文件夹中第一张图片
        self.picArray = []

        # 判断当前文件中是否存在以jpg、bmp、png为结尾的文件
        for root, dirs, files in os.walk(self.veinPath.text()):
            for file in files:
                # 检测的目标个数
                ext = os.path.splitext(file)[-1].lower()
                print(ext)
                if ext == '.jpg' or ext == '.bmp' or ext == '.png':
                    self.picArray.append(file)
                    # print(self.picArray)
        if len(self.picArray) > 0:
            self.DirFirstPicPath = self.veinPathSave.text() + '/' + self.picArray[0]
            # 显示文件夹中的第一个图片
            jpg = QtGui.QPixmap(self.DirFirstPicPath).scaled(self.aug_after_vein.width(), self.aug_after_vein.height())
            self.aug_after_vein.setPixmap(jpg)
        else:
            QMessageBox.information(self, '提示', '当前选择文件夹中不存在以jpg、bmp、png结尾的图片文件，请重新选择！', QMessageBox.Yes)

        # 选择纹理增广结果保存路径
    def onSelectVeinFileDir(self):
        # 选择文件夹路径
        self.veinPath.setText(QFileDialog.getExistingDirectory(self, '请选择待检文件夹'))
        # 调整检测类型为文件夹多张
        self.detectType = 2
        # 选择文件夹时 仅展示文件夹中第一张图片
        self.picArray = []

        # 判断当前文件中是否存在以jpg、bmp、png为结尾的文件
        for root, dirs, files in os.walk(self.veinPath.text()):
            for file in files:
                # 检测的目标个数
                ext = os.path.splitext(file)[-1].lower()
                print(ext)
                if ext == '.jpg' or ext == '.bmp' or ext == '.png':
                    self.picArray.append(file)
                    # print(self.picArray)

        # 当文件夹中图片的个数大于0的时候才会展示一张出来
        if len(self.picArray) > 0:
            self.DirFirstPicPath = self.veinPath.text() + '/' + self.picArray[0]
            # 显示文件夹中的第一个图片
            jpg = QtGui.QPixmap(self.DirFirstPicPath).scaled(self.aug_pre_vein.width(), self.aug_pre_vein.height())
            self.aug_pre_vein.setPixmap(jpg)

        else:
            QMessageBox.information(self, '提示', '当前选择文件夹中不存在以jpg、bmp、png结尾的图片文件，请重新选择！', QMessageBox.Yes)

    # 选择标签路径
    def onSelectVeinLabelPath(self):
        self.veinPathLabel.setText(QFileDialog.getExistingDirectory())

    # 选择纹理增广结果保存路径
    def onSelectVeinSavePath(self):
        self.veinPathSave.setText(QFileDialog.getExistingDirectory())

    # 纹理增广方法
    def onVeinPic(self):
        # 获取文件下属性为imgProperty的所有文件
        def GetImgNameByEveryDir(file_dir, imgProperty):
            FileName = []
            for root, dirs, files in os.walk(file_dir):
                for file in files:
                    if os.path.splitext(file)[1] in imgProperty:
                        FileName.append(file)  # 保存图片名称
            return FileName

        def readBoxes(txt_path):
            boxes = []
            with open(txt_path) as file:
                txt_lines = file.readlines()
                for txt_line in txt_lines:
                    box = txt_line.rstrip().split(" ")
                    boxes.append([int(box[0]), float(box[1]), float(box[2]), float(box[3]), float(box[4])])

            return boxes

        image_path = self.veinPath.text()
        label_path = self.veinPathLabel.text()
        output_path = self.veinPathSave.text()

        vein = str(self.VeinPara.currentText())

        def get_class_value(className):
            if className == "高斯噪声":
                return 0
            elif className == "高斯扰动":
                return 1

        veinId = get_class_value(vein)

        img_list = GetImgNameByEveryDir(image_path, ['.jpg', '.jpeg', '.bmp'])
        for img_name in tqdm(img_list):
            img_is_ok = 1
            boxes = []
            img_path = image_path + '\\' + img_name
            try:
                img = np.array(Image.open(img_path).convert('RGB'), dtype=np.uint8)
                img1 = cv2.imread(img_path)
            except Exception as e:
                print(f"could not read image '{img_path}'. ")
                img_is_ok = 0
            if img_is_ok:  # 如果图像存在，读取对应的标签文件
                label_name = img_name[:-3] + 'txt'
                txt_path = label_path + '\\' + label_name
                boxes = readBoxes(txt_path)
                print(boxes)

            if veinId == 0:

                if not os.path.exists(output_path):
                    os.makedirs(output_path)
                if not os.path.exists(os.path.join(output_path, 'Noise')):
                    os.makedirs(os.path.join(output_path, 'Noise'))
                if not os.path.exists(os.path.join(output_path, 'Noise', 'aug_img')):
                    os.makedirs(os.path.join(output_path, 'Noise', 'aug_img'))
                if not os.path.exists(os.path.join(output_path, 'Noise', 'aug_label')):
                    os.makedirs(os.path.join(output_path, 'Noise', 'aug_label'))
                    # 在aug_label文件夹创建classes.txt文件
                    with open(os.path.join(output_path, 'Noise', 'aug_label', 'classes.txt'), 'w') as f:
                        f.write('Granular sludge\n')
                        f.write('Epistylis\n')
                        f.write('Floc\n')
                        f.write('Rotifer\n')
                        f.write('Filamentous bacteria\n')

                transform = aug_tools.augmentations.AUGMENTATION_TRANSFORMS_GaussianNoise
                boxes = np.array(boxes)
                temp_boxes = np.zeros_like(boxes)
                temp_boxes[:, :] = boxes[:, :]
                #
                # copy_num为对同一张图片扩充的张数
                copy_num = 1  # 增强张数
                for i in np.arange(copy_num):
                    new_img, bb_target = transform((img1, boxes))
                    save_name = img_name[:-4] + "_Noise_" + str(i)
                    cv2.imwrite(os.path.join(output_path, 'Noise', 'aug_img', save_name + '.bmp'), new_img)
                    txt_file = open(os.path.join(output_path, 'Noise', 'aug_label', save_name + '.txt'), 'w')
                    for line in bb_target:
                        bb = str(int(line[0])) + ' ' + str(line[1]) + ' ' + str(line[2]) + ' ' + str(
                            line[3]) + ' ' + str(
                            line[4]) + '\n'
                        txt_file.write(bb)
                    txt_file.close()
                    boxes[:, :] = temp_boxes[:, :]
                veinPath = self.veinPathSave.text() + '/' + 'Noise' + '/' + 'aug_img'


            elif veinId == 1:

                if not os.path.exists(output_path):
                    os.makedirs(output_path)
                if not os.path.exists(os.path.join(output_path, 'Blur')):
                    os.makedirs(os.path.join(output_path, 'Blur'))
                if not os.path.exists(os.path.join(output_path, 'Blur', 'aug_img')):
                    os.makedirs(os.path.join(output_path, 'Blur', 'aug_img'))
                if not os.path.exists(os.path.join(output_path, 'Blur', 'aug_label')):
                    os.makedirs(os.path.join(output_path, 'Blur', 'aug_label'))
                    # 在aug_label文件夹创建classes.txt文件
                    with open(os.path.join(output_path, 'Blur', 'aug_label', 'classes.txt'), 'w') as f:
                        f.write('Granular sludge\n')
                        f.write('Epistylis\n')
                        f.write('Floc\n')
                        f.write('Rotifer\n')
                        f.write('Filamentous bacteria\n')

                transform = aug_tools.augmentations.AUGMENTATION_TRANSFORMS_Blur
                boxes = np.array(boxes)
                temp_boxes = np.zeros_like(boxes)
                temp_boxes[:, :] = boxes[:, :]
                #
                # copy_num为对同一张图片扩充的张数
                copy_num = 1  # 增强张数
                for i in np.arange(copy_num):
                    new_img, bb_target = transform((img1, boxes))
                    save_name = img_name[:-4] + "_Blur_" + str(i)
                    cv2.imwrite(os.path.join(output_path, 'Blur', 'aug_img', save_name + '.bmp'), new_img)
                    txt_file = open(os.path.join(output_path, 'Blur', 'aug_label', save_name + '.txt'), 'w')
                    for line in bb_target:
                        bb = str(int(line[0])) + ' ' + str(line[1]) + ' ' + str(line[2]) + ' ' + str(
                            line[3]) + ' ' + str(
                            line[4]) + '\n'
                        txt_file.write(bb)
                    txt_file.close()
                    boxes[:, :] = temp_boxes[:, :]
                veinPath = self.veinPathSave.text() + '/' + 'Blur' + '/' + 'aug_img'

        self.picArray = []
        # reversePath = self.reversePathSave.text() + '/' + 'reverse' + '/' + 'aug_img'
        for root, dirs, files in os.walk(veinPath):
            for file in files:
                # 检测的目标个数
                ext = os.path.splitext(file)[-1].lower()
                print(ext)
                if ext == '.jpg' or ext == '.bmp' or ext == '.png':
                    self.picArray.append(file)

        if len(self.picArray) > 0:
            self.DirFirstPicPath = veinPath + '/' + self.picArray[0]
            # 显示文件夹中的第一个图片
            jpg = QtGui.QPixmap(self.DirFirstPicPath).scaled(self.aug_after_vein.width(), self.aug_after_vein.height())
            self.aug_after_vein.setPixmap(jpg)

        else:
            QMessageBox.information(self, '提示', '当前选择文件夹中不存在以jpg、bmp、png结尾的图片文件，请重新选择！', QMessageBox.Yes)

    # 选择图片翻转增广图片文件夹
    def onSelectReverseFileDir(self):
        # 选择文件夹路径
        self.reversePath.setText(QFileDialog.getExistingDirectory(self, '请选择待检文件夹'))
        # 调整检测类型为文件夹多张
        self.detectType = 2
        # 选择文件夹时 仅展示文件夹中第一张图片
        self.picArray = []

        # 判断当前文件中是否存在以jpg、bmp、png为结尾的文件
        for root, dirs, files in os.walk(self.reversePath.text()):
            for file in files:
                # 检测的目标个数
                ext = os.path.splitext(file)[-1].lower()
                print(ext)
                if ext == '.jpg' or ext == '.bmp' or ext == '.png':
                    self.picArray.append(file)
                    # print(self.picArray)

        # 当文件夹中图片的个数大于0的时候才会展示一张出来
        if len(self.picArray) > 0:
            self.DirFirstPicPath = self.reversePath.text() + '/' + self.picArray[0]
            # 显示文件夹中的第一个图片
            jpg = QtGui.QPixmap(self.DirFirstPicPath).scaled(self.aug_pre_reverse.width(),
                                                             self.aug_pre_reverse.height())
            self.aug_pre_reverse.setPixmap(jpg)

        else:
            QMessageBox.information(self, '提示', '当前选择文件夹中不存在以jpg、bmp、png结尾的图片文件，请重新选择！', QMessageBox.Yes)

        # 选择图片翻转增广标签文件夹

    def onSelectReverseLabelPath(self):
        self.reversePathLabel.setText(QFileDialog.getExistingDirectory())

        # 选择图片翻转增广结果保存路径

    def onSelectReverseSavePath(self):
        self.reversePathSave.setText(QFileDialog.getExistingDirectory())

    # 图片翻转增广方法
    def onReversePic(self):
        # 获取文件下属性为imgProperty的所有文件
        def GetImgNameByEveryDir(file_dir, imgProperty):
            FileName = []
            for root, dirs, files in os.walk(file_dir):
                for file in files:
                    if os.path.splitext(file)[1] in imgProperty:
                        FileName.append(file)  # 保存图片名称
            return FileName

        def readBoxes(txt_path):
            boxes = []
            with open(txt_path) as file:
                txt_lines = file.readlines()
                for txt_line in txt_lines:
                    box = txt_line.rstrip().split(" ")
                    boxes.append([int(box[0]), float(box[1]), float(box[2]), float(box[3]), float(box[4])])

            return boxes

        image_path = self.reversePath.text()
        label_path = self.reversePathLabel.text()
        output_path = self.reversePathSave.text()

        geo = str(self.FlipPara.currentText())

        def get_class_value(className):
            if className == "水平翻转":
                return 0
            elif className == "上下翻转":
                return 1
            elif className == "随机旋转":
                return 2

        geoId = get_class_value(geo)

        img_list = GetImgNameByEveryDir(image_path, ['.jpg', '.jpeg', '.bmp'])
        for img_name in tqdm(img_list):
            img_is_ok = 1
            boxes = []
            img_path = image_path + '\\' + img_name
            try:
                img = np.array(Image.open(img_path).convert('RGB'), dtype=np.uint8)
                img1 = cv2.imread(img_path)
            except Exception as e:
                print(f"could not read image '{img_path}'. ")
                img_is_ok = 0
            if img_is_ok:  # 如果图像存在，读取对应的标签文件
                label_name = img_name[:-3] + 'txt'
                txt_path = label_path + '\\' + label_name
                boxes = readBoxes(txt_path)
                print(boxes)

            if geoId == 0:

                if not os.path.exists(output_path):
                    os.makedirs(output_path)
                if not os.path.exists(os.path.join(output_path, 'Fliplr')):
                    os.makedirs(os.path.join(output_path, 'Fliplr'))
                if not os.path.exists(os.path.join(output_path, 'Fliplr', 'aug_img')):
                    os.makedirs(os.path.join(output_path, 'Fliplr', 'aug_img'))
                if not os.path.exists(os.path.join(output_path, 'Fliplr', 'aug_label')):
                    os.makedirs(os.path.join(output_path, 'Fliplr', 'aug_label'))
                    # 在aug_label文件夹创建classes.txt文件
                    with open(os.path.join(output_path, 'Fliplr', 'aug_label', 'classes.txt'), 'w') as f:
                        f.write('Granular sludge\n')
                        f.write('Epistylis\n')
                        f.write('Floc\n')
                        f.write('Rotifer\n')
                        f.write('Filamentous bacteria\n')

                transform = aug_tools.augmentations.AUGMENTATION_TRANSFORMS_Fliplr
                boxes = np.array(boxes)
                temp_boxes = np.zeros_like(boxes)
                temp_boxes[:, :] = boxes[:, :]
                #
                # copy_num为对同一张图片扩充的张数
                copy_num = 1  # 增强张数
                for i in np.arange(copy_num):
                    new_img, bb_target = transform((img1, boxes))
                    save_name = img_name[:-4] + "_Fliplr_" + str(i)
                    cv2.imwrite(os.path.join(output_path, 'Fliplr', 'aug_img', save_name + '.bmp'), new_img)
                    txt_file = open(os.path.join(output_path, 'Fliplr', 'aug_label', save_name + '.txt'), 'w')
                    for line in bb_target:
                        bb = str(int(line[0])) + ' ' + str(line[1]) + ' ' + str(line[2]) + ' ' + str(
                            line[3]) + ' ' + str(
                            line[4]) + '\n'
                        txt_file.write(bb)
                    txt_file.close()
                    boxes[:, :] = temp_boxes[:, :]
                reversePath = self.reversePathSave.text() + '/' + 'Fliplr' + '/' + 'aug_img'


            elif geoId == 1:

                if not os.path.exists(output_path):
                    os.makedirs(output_path)
                if not os.path.exists(os.path.join(output_path, 'Flipud')):
                    os.makedirs(os.path.join(output_path, 'Flipud'))
                if not os.path.exists(os.path.join(output_path, 'Flipud', 'aug_img')):
                    os.makedirs(os.path.join(output_path, 'Flipud', 'aug_img'))
                if not os.path.exists(os.path.join(output_path, 'Flipud', 'aug_label')):
                    os.makedirs(os.path.join(output_path, 'Flipud', 'aug_label'))
                    # 在aug_label文件夹创建classes.txt文件
                    with open(os.path.join(output_path, 'Flipud', 'aug_label', 'classes.txt'), 'w') as f:
                        f.write('Granular sludge\n')
                        f.write('Epistylis\n')
                        f.write('Floc\n')
                        f.write('Rotifer\n')
                        f.write('Filamentous bacteria\n')

                transform = aug_tools.augmentations.AUGMENTATION_TRANSFORMS_Flipud
                boxes = np.array(boxes)
                temp_boxes = np.zeros_like(boxes)
                temp_boxes[:, :] = boxes[:, :]
                #
                # copy_num为对同一张图片扩充的张数
                copy_num = 1  # 增强张数
                for i in np.arange(copy_num):
                    new_img, bb_target = transform((img1, boxes))
                    save_name = img_name[:-4] + "_Flipud_" + str(i)
                    cv2.imwrite(os.path.join(output_path, 'Flipud', 'aug_img', save_name + '.bmp'), new_img)
                    txt_file = open(os.path.join(output_path, 'Flipud', 'aug_label', save_name + '.txt'), 'w')
                    for line in bb_target:
                        bb = str(int(line[0])) + ' ' + str(line[1]) + ' ' + str(line[2]) + ' ' + str(
                            line[3]) + ' ' + str(
                            line[4]) + '\n'
                        txt_file.write(bb)
                    txt_file.close()
                    boxes[:, :] = temp_boxes[:, :]
                reversePath = self.reversePathSave.text() + '/' + 'Flipud' + '/' + 'aug_img'

            elif geoId == 2:

                if not os.path.exists(output_path):
                    os.makedirs(output_path)
                if not os.path.exists(os.path.join(output_path, 'Rotate')):
                    os.makedirs(os.path.join(output_path, 'Rotate'))
                if not os.path.exists(os.path.join(output_path, 'Rotate', 'aug_img')):
                    os.makedirs(os.path.join(output_path, 'Rotate', 'aug_img'))
                if not os.path.exists(os.path.join(output_path, 'Rotate', 'aug_label')):
                    os.makedirs(os.path.join(output_path, 'Rotate', 'aug_label'))
                    # 在aug_label文件夹创建classes.txt文件
                    with open(os.path.join(output_path, 'Rotate', 'aug_label', 'classes.txt'), 'w') as f:
                        f.write('Granular sludge\n')
                        f.write('Epistylis\n')
                        f.write('Floc\n')
                        f.write('Rotifer\n')
                        f.write('Filamentous bacteria\n')

                transform = aug_tools.augmentations.AUGMENTATION_TRANSFORMS_Rotate
                boxes = np.array(boxes)
                temp_boxes = np.zeros_like(boxes)
                temp_boxes[:, :] = boxes[:, :]
                #
                # copy_num为对同一张图片扩充的张数
                copy_num = 1  # 增强张数
                for i in np.arange(copy_num):
                    new_img, bb_target = transform((img1, boxes))
                    save_name = img_name[:-4] + "_Rotate_" + str(i)
                    cv2.imwrite(os.path.join(output_path, 'Rotate', 'aug_img', save_name + '.bmp'), new_img)
                    txt_file = open(os.path.join(output_path, 'Rotate', 'aug_label', save_name + '.txt'), 'w')
                    for line in bb_target:
                        bb = str(int(line[0])) + ' ' + str(line[1]) + ' ' + str(line[2]) + ' ' + str(
                            line[3]) + ' ' + str(
                            line[4]) + '\n'
                        txt_file.write(bb)
                    txt_file.close()
                    boxes[:, :] = temp_boxes[:, :]
                reversePath = self.reversePathSave.text() + '/' + 'Rotate' + '/' + 'aug_img'

        self.picArray = []
        # reversePath = self.reversePathSave.text() + '/' + 'reverse' + '/' + 'aug_img'
        for root, dirs, files in os.walk(reversePath):
            for file in files:
                # 检测的目标个数
                ext = os.path.splitext(file)[-1].lower()
                print(ext)
                if ext == '.jpg' or ext == '.bmp' or ext == '.png':
                    self.picArray.append(file)

        if len(self.picArray) > 0:
            self.DirFirstPicPath = reversePath + '/' + self.picArray[0]
            # 显示文件夹中的第一个图片
            jpg = QtGui.QPixmap(self.DirFirstPicPath).scaled(self.aug_after_reverse.width(),
                                                             self.aug_after_reverse.height())
            self.aug_after_reverse.setPixmap(jpg)

        else:
            QMessageBox.information(self, '提示', '当前选择文件夹中不存在以jpg、bmp、png结尾的图片文件，请重新选择！', QMessageBox.Yes)

        # gan增广方法结果保存路径  gan增广不需要选择图片和标签  通过模型进行增广

    # gan增广结果保存路径
    def onSelectGANSavePath(self):
        self.ganPathSave.setText(QFileDialog.getExistingDirectory())

    # gan增广方法
    def onGANPic(self):
        out = './out'
        out_path = self.ganPathSave.text()

        class_name = str(self.ganClassPara.currentText())
        network = './weights/' + class_name + '.pkl'

        if not os.path.exists(out_path):
            os.makedirs(out_path)
        if not os.path.exists(os.path.join(out_path, 'GAN_' + class_name)):
            os.makedirs(os.path.join(out_path, 'GAN_' + class_name))
        if not os.path.exists(os.path.join(out_path, 'GAN_' + class_name, 'aug_img')):
            os.makedirs(os.path.join(out_path, 'GAN_' + class_name, 'aug_img'))
        if not os.path.exists(os.path.join(out_path, 'GAN_' + class_name, 'aug_label')):
            os.makedirs(os.path.join(out_path, 'GAN_' + class_name, 'aug_label'))
            # 在aug_label文件夹创建classes.txt文件
            with open(os.path.join(out_path, 'GAN_' + class_name, 'aug_label', 'classes.txt'), 'w') as f:
                f.write('Granular sludge\n')
                f.write('Epistylis\n')
                f.write('Floc\n')
                f.write('Rotifer\n')
                f.write('Filamentous bacteria\n')

        out_image = out_path + '/GAN_' + class_name + '/aug_img'
        out_label = out_path + '/GAN_' + class_name + '/aug_label'

        def get_class_value(className):
            if className == "GranularSludge":
                return 0
            elif className == "Epistylis":
                return 1
            elif className == "Floc":
                return 2
            elif className == "Rotifer":
                return 3
            elif className == "FilamentousBacteria":
                return 4

        classId = get_class_value(class_name)

        BigNumber = int(self.ganNumPara.currentText())
        SmallNumber = BigNumber * 10
        arr = [i for i in range(1, SmallNumber + 1)]

        trunc = 1

        def clear_folder(folder_path):
            for filename in os.listdir(folder_path):
                file_path = os.path.join(folder_path, filename)
                try:
                    if os.path.isfile(file_path) or os.path.islink(file_path):
                        os.unlink(file_path)
                    elif os.path.isdir(file_path):
                        shutil.rmtree(file_path)
                except Exception as e:
                    print('Failed to delete %s. Reason: %s' % (file_path, e))

        clear_folder(out)

        gen_images.generate_images(network_pkl=network,
                                   seeds=arr,
                                   truncation_psi=trunc,
                                   noise_mode='const',
                                   outdir=out,
                                   translate=(0, 0),
                                   rotate=0,
                                   class_idx=None)

        joint.create_large_image_and_yolo_labels(input_folder=out,
                                                 output_image_folder=out_image,
                                                 output_label_folder=out_label,
                                                 class_id=classId)

        self.picArray = []
        for root, dirs, files in os.walk(out_image):
            for file in files:
                # 检测的目标个数
                ext = os.path.splitext(file)[-1].lower()
                print(ext)
                if ext == '.jpg' or ext == '.bmp' or ext == '.png':
                    self.picArray.append(file)

        if len(self.picArray) > 0:
            self.DirFirstPicPath = out_image + '/' + self.picArray[0]
            # 显示文件夹中的第一个图片
            jpg = QtGui.QPixmap(self.DirFirstPicPath).scaled(self.aug_after_gan.width(), self.aug_after_gan.height())
            self.aug_after_gan.setPixmap(jpg)

        else:
            QMessageBox.information(self, '提示', '当前选择文件夹中不存在以jpg、bmp、png结尾的图片文件，请重新选择！', QMessageBox.Yes)

    # 按间距中的绿色按钮以运行脚本。


def main():
    app = QApplication([])
    app.setStyle(QStyleFactory.create("Windows"))
    window = MainApp()
    window.showMaximized()
    app.exec_()


if __name__ == '__main__':
    main()
